using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.ComponentModel;
using System.Net;
using System.Web.Services;
using System.IO;
using System.Reflection;
using SharePointSearchBench.Library;
using SharePointSearchBench.Library.Logging;
//using Microsoft.Office.Server.Search.Query;

namespace SharePointSearchBench
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window, IDisposable
    {
        SavedStringCollection savedUrls;
        SavedStringCollection savedDomains;
        SavedStringCollection savedUsernames;
        BackgroundWorker backgroundWorker;
        DataTable results;
        string currentSavePath;
        bool isDirty;
        bool loading;
        bool disposed;

        /// <summary>
        /// Creates a new instance of the class.
        /// </summary>
        public MainWindow()
        {

            DebugLogWriter.WriteMessage("MainWindow constructor.");

            loading = true;
            InitializeComponent();
            currentSavePath = string.Empty;
            this.InitializeWebServiceUrlComboBox();
            this.InitializeDomainComboBox();
            this.InitializeUsernameComboBox();
            this.InitializeBackgroundWorker();
            this.UpdateInfo("Ready.");
            loading = false;
        }

        void MarkDirty()
        {
            if(!loading)
            {
                this.isDirty = true;
            }
        }

        void InitializeBackgroundWorker()
        {
            this.backgroundWorker = new BackgroundWorker();
            this.backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
            this.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
            this.backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
        }

        void DisableUiForQuery()
        {
            this.resultsListView.IsEnabled = false;
            this.executeButton.IsEnabled = false;
            this.domainComboBox.IsEnabled = false;
            this.usernameComboBox.IsEnabled = false;
            this.passwordTextBox.IsEnabled = false;
            this.queryTextBox.IsEnabled = false;
            this.keywordPhraseTextBox.IsEnabled = false;
            this.keywordFieldsTextBox.IsEnabled = false;
            this.keywordSortFieldsTextBox.IsEnabled = false;
            this.keywordButton.IsEnabled = false;
            this.fullTextButton.IsEnabled = false;
            this.webServiceButton.IsEnabled = false;
            this.objectModelButton.IsEnabled = false;
            this.webServiceUrlComboBox.IsEnabled = false;
            this.numberOfResultsTextBox.IsEnabled = false;
            this.scopesListBox.IsEnabled = false;
            this.managedPropertiesListBox.IsEnabled = false;
            this.refreshMetadataButton.IsEnabled = false;
            this.startAtTextBox.IsEnabled = false;
            this.relevantResultsButton.IsEnabled = false;
            this.highConfidenceResultsButton.IsEnabled = false;
            this.specialTermsResultsButton.IsEnabled = false;
        }

        void EnableUiForQuery()
        {
            this.resultsListView.IsEnabled = true;
            this.executeButton.IsEnabled = true;
            this.domainComboBox.IsEnabled = true;
            this.usernameComboBox.IsEnabled = true;
            this.passwordTextBox.IsEnabled = true;
            this.queryTextBox.IsEnabled = true;
            this.keywordPhraseTextBox.IsEnabled = true;
            this.keywordFieldsTextBox.IsEnabled = true;
            this.keywordSortFieldsTextBox.IsEnabled = true;
            this.keywordButton.IsEnabled = true;
            this.fullTextButton.IsEnabled = true;
            this.webServiceButton.IsEnabled = true;
            this.objectModelButton.IsEnabled = true;
            this.webServiceUrlComboBox.IsEnabled = true;
            this.numberOfResultsTextBox.IsEnabled = true;
            this.scopesListBox.IsEnabled = true;
            this.managedPropertiesListBox.IsEnabled = true;
            this.refreshMetadataButton.IsEnabled = true;
            this.startAtTextBox.IsEnabled = true;
            this.relevantResultsButton.IsEnabled = true;
            this.highConfidenceResultsButton.IsEnabled = true;
            this.specialTermsResultsButton.IsEnabled = true;
        }

        void InitializeUsernameComboBox()
        {
            this.savedUsernames = new SavedStringCollection();
            this.savedUsernames.SaveFileName = "SavedUsernames.xml";
            this.savedUsernames.Load();
            this.usernameComboBox.ItemsSource = this.savedUsernames;
        }

        void InitializeWebServiceUrlComboBox()
        {
            this.savedUrls = new SavedStringCollection();
            this.savedUrls.SaveFileName = "SavedUrls.xml";
            this.savedUrls.Load();
            this.webServiceUrlComboBox.ItemsSource = this.savedUrls;
        }

        void InitializeDomainComboBox()
        {
            this.savedDomains = new SavedStringCollection();
            this.savedDomains.SaveFileName = "SavedDomains.xml";
            this.savedDomains.Load();
            this.domainComboBox.ItemsSource = this.savedDomains;
        }

        protected override void OnClosed(EventArgs e)
        {
            RecentFileCollection recentFiles = this.GetRecentFiles();
            recentFiles.Save();
            this.savedUrls.Save();
            this.savedDomains.Save();
            this.savedUsernames.Save();
            base.OnClosed(e);
        }

        void UpdateComboBoxSourceData()
        {
            if(this.webServiceUrlComboBox.Text.Trim().Length > 0 && !this.savedUrls.Contains(this.webServiceUrlComboBox.Text))
            {
                this.savedUrls.Insert(0, this.webServiceUrlComboBox.Text);
            }

            if(this.domainComboBox.Text.Trim().Length > 0 && !this.savedDomains.Contains(this.domainComboBox.Text))
            {
                this.savedDomains.Insert(0, this.domainComboBox.Text);
            }

            if(this.usernameComboBox.Text.Trim().Length > 0 && !this.savedUsernames.Contains(this.usernameComboBox.Text))
            {
                this.savedUsernames.Insert(0, this.usernameComboBox.Text);
            }

        }

        void HandleError(Exception ex)
        {
            using (IDisposableLogWriter logger = new DisposableDebugLogWriter())
            {
                this.EnableUiForQuery();
                this.UpdateInfo("An error occurred.");
                this.errorTextBox.Text = ex.ToString();
                logger.WriteMessage(ex.ToString());


                logger.WriteMessage("Exception message: " + ex.GetType().FullName + " " + ex.Message);
                Exception inner = ex.InnerException;
                while (inner != null)
                {
                    logger.WriteMessage("Inner Exception message: " + inner.GetType().FullName + " " + inner.Message);
                    inner = inner.InnerException;
                }


                if (ex is System.Web.Services.Protocols.SoapException)
                {
                    System.Web.Services.Protocols.SoapException soapEx = ex as System.Web.Services.Protocols.SoapException;
                    this.errorTextBox.Text += soapEx.Detail.InnerText;
                }

                this.errorTextBox.Visibility = Visibility.Visible;
            }
        }

        void UpdateResultsGrid()
        {
            Binding binding = new Binding();
            this.resultsListView.DataContext = this.results;
            this.resultsListView.SetBinding(ListView.ItemsSourceProperty, binding);

            this.resultsGridView.Columns.Clear();
            foreach(DataColumn column in this.results.Columns)
            {
                GridViewColumn gridColumn = new GridViewColumn();
                gridColumn.DisplayMemberBinding = new Binding(column.ColumnName);
                gridColumn.Header = column.ColumnName;
                gridColumn.Width = 100;
                this.resultsGridView.Columns.Add(gridColumn);
            }

        }


        void UpdateInfo(string message)
        {
            this.infoTextBlock.Text = message;
        }

        static string GetDefaultDialogPath()
        {
            string assemblyPath = Assembly.GetExecutingAssembly().Location;
            FileInfo assemblyFile = new FileInfo(assemblyPath);
            DirectoryInfo folder = assemblyFile.Directory;
            return folder.FullName;
        }

        void PerformOpen(string path)
        {
            if(this.isDirty)
            {
                MessageBoxResult saveResult = MessageBox.Show("Would you like to save your current session?", "Save Session", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                if(saveResult == MessageBoxResult.Yes)
                {
                    this.PerformSave();
                }
                else if(saveResult == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            if(string.IsNullOrEmpty(path))
            {
                System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
                dialog.InitialDirectory = MainWindow.GetDefaultDialogPath();
                dialog.Filter = "spsb files (*.spsb)|*.spsb";
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();

                if(result == System.Windows.Forms.DialogResult.OK)
                {
                    this.currentSavePath = dialog.FileName;
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.currentSavePath = path;
            }

            AppSessionState.LoadFromState(currentSavePath, this);
            this.isDirty = false;

        }

        void PerformOpen()
        {
            this.PerformOpen(null);
        }

        void PerformSave()
        {
            if(string.IsNullOrEmpty(this.currentSavePath))
            {
                this.PerformSaveAs();
            }
            else
            {
                AppSessionState.SaveState(this, this.currentSavePath);
                this.isDirty = false;
            }
        }

        void PerformSaveAs()
        {
            System.Windows.Forms.SaveFileDialog saveDialog = new System.Windows.Forms.SaveFileDialog();
            saveDialog.Filter = "spsb files (*.spsb)|*.spsb";
            saveDialog.InitialDirectory = MainWindow.GetDefaultDialogPath();
            System.Windows.Forms.DialogResult result = saveDialog.ShowDialog();

            if(result == System.Windows.Forms.DialogResult.OK)
            {
                string path = saveDialog.FileName;
                AppSessionState.SaveState(this, path);
                this.currentSavePath = path;
                this.isDirty = false;

                FileInfo fileInfo = new FileInfo(path);
                RecentFile recentFile = new RecentFile();
                recentFile.Path = path;
                recentFile.Name = fileInfo.Name;
                recentFile.UsageDate = DateTime.Now;
                RecentFileCollection recentFiles = this.GetRecentFiles();
                recentFiles.Add(recentFile);
            }
        }

        RecentFileCollection GetRecentFiles()
        {
            return this.recentFilesMenuItem.ItemsSource as RecentFileCollection;
        }

        protected override void OnClosing(CancelEventArgs e)
        {

            if(this.isDirty)
            {
                MessageBoxResult result = MessageBox.Show("Would you like to save your current session?", "Save Session", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                if(result == MessageBoxResult.Yes)
                {
                    this.PerformSave();
                }
                else if (result == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
            }

            base.OnClosing(e);
        }

        Search DoQueryWork(DoWorkEventArgs e)
        {
            Search search = e.Argument as Search;
            try
            {
                DebugLogWriter.WriteMessage("DoQueryWork");
                DebugLogWriter.WriteMessage("Executing...");
                DataSet resultSet = search.Execute();
                this.results = resultSet.Tables[0];
                DebugLogWriter.WriteMessage("Got results back.  Returning search object.");
            }
            catch (Exception ex)
            {
                DebugLogWriter.WriteMessage(ex.ToString());
                this.HandleError(ex);
            }
            return search;
        }

        void AboutClick(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        void ControlChanged(object sender, EventArgs e)
        {
            this.MarkDirty();
        }

        void QueryTypeButtonChecked(object sender, EventArgs e)
        {
            if(this.keywordButton == null || this.fullTextButton == null)
            {
                return;
            }

            this.MarkDirty();

            if(this.keywordButton.IsChecked.Equals(true))
            {
                this.keywordFieldsBorder.Visibility = Visibility.Visible;
                this.keywordPhraseBorder.Visibility = Visibility.Visible;
                this.keywordSortFieldsBorder.Visibility = Visibility.Visible;

                this.fullTextBorder.Visibility = Visibility.Collapsed;
            }
            else if(this.fullTextButton.IsChecked.Equals(true))
            {
                this.keywordFieldsBorder.Visibility = Visibility.Collapsed;
                this.keywordPhraseBorder.Visibility = Visibility.Collapsed;
                this.keywordSortFieldsBorder.Visibility = Visibility.Collapsed;
                this.fullTextBorder.Visibility = Visibility.Visible;
            }
            else
            {
                this.keywordFieldsBorder.Visibility = Visibility.Collapsed;
                this.keywordPhraseBorder.Visibility = Visibility.Collapsed;
                this.keywordSortFieldsBorder.Visibility = Visibility.Collapsed;
                this.fullTextBorder.Visibility = Visibility.Collapsed;
            }
        }

        void OpenCommandExecuted(object sender, EventArgs e)
        {
            this.PerformOpen();
        }

        void SaveCommandExecuted(object sender, EventArgs e)
        {
            this.PerformSave();
        }

        void SaveAsCommandExecuted(object sender, EventArgs e)
        {
            this.PerformSaveAs();
        }
        
        void CloseCommandExecuted(object sender, EventArgs e)
        {
            this.Close();
        }
        
        void RefreshMetadataClick(object sender, EventArgs e)
        {
            try
            {
                this.DisableUiForQuery();

                Search search = new Search();
                search.ContextUri = new Uri(this.webServiceUrlComboBox.Text);
                if (this.webServiceButton.IsChecked.Equals(true))
                {
                    search.ApiSource = ApiSource.Service;
                    NetworkCredential credentials = new NetworkCredential(
                        this.usernameComboBox.Text, this.passwordTextBox.Password, this.domainComboBox.Text);
                    search.Credentials = credentials;
                }
                else
                {
                    search.ApiSource = ApiSource.ObjectModel;
                }

                Collection<SearchScope> scopes = search.SearchScopes;
                Collection<SearchProperty> properties = search.SearchProperties;

                this.scopesListBox.ItemsSource = scopes;
                this.managedPropertiesListBox.ItemsSource = properties;
                this.UpdateComboBoxSourceData();
            }
            catch (SharePointSearchBenchException benchException)
            {
                this.HandleError(benchException);
            }
            catch (UriFormatException uriEx)
            {
                this.HandleError(uriEx);
            }
            catch (WebException webEx)
            {
                this.HandleError(webEx);
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                this.HandleError(soapEx);
            }
            catch (Exception ex)
            {
                this.HandleError(ex);
            }
            finally
            {
                this.EnableUiForQuery();
            }
        }
        
        void RecentFileMenuItemClick(object sender, RoutedEventArgs e)
        {
            RecentFile recentFile = ((MenuItem)e.OriginalSource).Header as RecentFile;
            this.PerformOpen(recentFile.Path);
        }
        
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = this.DoQueryWork(e);
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                DebugLogWriter.WriteMessage("backgroundWorker_RunWorkerCompleted: BEGIN");

                Search search = e.Result as Search;

                DebugLogWriter.WriteMessage("Enabling UI for query...");
                this.EnableUiForQuery();

                DebugLogWriter.WriteMessage("Updating results grid...");
                this.UpdateResultsGrid();

                DebugLogWriter.WriteMessage("Updating info...");
                this.UpdateInfo("Found " + results.Rows.Count.ToString() + " results.");

                if(search.ApiSource == ApiSource.ObjectModel)
                {
                    this.queryXmlTextBox.Text = string.Empty;
                    this.queryXmlBorder.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.queryXmlBorder.Visibility = Visibility.Collapsed;
                    if(!string.IsNullOrEmpty(search.FinalQueryXml))
                    {
                        this.queryXmlTextBox.Text = search.FinalQueryXml;
                    }
                    else
                    {
                        this.queryXmlTextBox.Text = string.Empty;
                    }
                }
            }
            catch(System.Reflection.TargetInvocationException targetEx)
            {
                this.HandleError(targetEx);
            }
            catch(System.Net.WebException webEx)
            {
                this.HandleError(webEx);
            }
            finally
            {
                DebugLogWriter.WriteMessage("backgroundWorker_RunWorkerCompleted: END");
            }

        }

        void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        void ObjectModelButtonChecked(object sender, EventArgs e)
        {
            this.MarkDirty();
            if(this.webServiceConnectionPanel != null)
            {
                this.webServiceConnectionPanel.Visibility = Visibility.Visible;
                this.UpdateInfo("Using object model.");
                this.webServiceUrlComboBox.IsEnabled = true;
                this.usernameComboBox.IsEnabled = false;
                this.passwordTextBox.IsEnabled = false;
                this.domainComboBox.IsEnabled = false;
            }
        }

        void WebServiceButtonChecked(object sender, EventArgs e)
        {
            this.MarkDirty();
            this.webServiceConnectionPanel.Visibility = Visibility.Visible;
            this.UpdateInfo("Using web service.");

            this.webServiceUrlComboBox.IsEnabled = true;
            this.usernameComboBox.IsEnabled = true;
            this.passwordTextBox.IsEnabled = true;
            this.domainComboBox.IsEnabled = true;
        }

        void ExecuteButtonClick(object sender, EventArgs e)
        {
            try
            {
                this.DisableUiForQuery();
                this.UpdateComboBoxSourceData();
                this.errorTextBox.Visibility = Visibility.Collapsed;

                this.queryXmlBorder.Visibility = Visibility.Collapsed;

                Search search = new Search();
                search.ContextUri = new Uri(this.webServiceUrlComboBox.Text);

                if (this.objectModelButton.IsChecked.Equals(true))
                {
                    search.ApiSource = ApiSource.ObjectModel;
                }
                else
                {
                    search.ApiSource = ApiSource.Service;
                    NetworkCredential credentials = new NetworkCredential(this.usernameComboBox.Text, this.passwordTextBox.Password, this.domainComboBox.Text);
                    search.Credentials = credentials;
                }

                if (this.keywordButton.IsChecked.Equals(true))
                {
                    search.SearchType = SearchType.Keyword;
                    search.SearchText = new SearchText(this.keywordPhraseTextBox.Text);

                    //load keyword view fields
                    string[] fields = this.keywordFieldsTextBox.Text.Split(',');
                    foreach (string field in fields)
                    {
                        search.DisplayFields.Add(field.Trim());
                    }

                    //load keyword sort fields
                    string[] sortFields = this.keywordSortFieldsTextBox.Text.Split(',');
                    foreach (string sortField in sortFields)
                    {
                        search.SortFields.Add(sortField.Trim());
                    }
                }
                else
                {
                    search.SearchType = SearchType.FullText;
                    search.SearchText = new SearchText(this.queryTextBox.Text);
                }

                search.StartAt = int.Parse(startAtTextBox.Text);
                search.ResultCount = int.Parse(this.numberOfResultsTextBox.Text);

                if (this.relevantResultsButton.IsChecked.Equals(true))
                {
                    search.SearchResultType = SearchResultType.Relevant;
                }

                if (this.highConfidenceResultsButton.IsChecked.Equals(true))
                {
                    search.SearchResultType = SearchResultType.HighConfidence;
                }

                if (this.specialTermsResultsButton.IsChecked.Equals(true))
                {
                    search.SearchResultType = SearchResultType.SpecialTerm;
                }

                this.backgroundWorker.RunWorkerAsync(search);
            }
            catch(FormatException formatEx)
            {
                this.HandleError(formatEx);
            }
            catch(NotImplementedException implementedEx)
            {
                this.HandleError(implementedEx);
            }
            catch(SharePointSearchBenchException benchException)
            {
                this.HandleError(benchException);
            }
        }

        /// <summary>
        /// Disposes the window.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing)
        {
            if(!this.disposed)
            {
                if(disposing)
                {
                    if(this.backgroundWorker != null)
                    {
                        this.backgroundWorker.Dispose();
                    }
                }

                disposed = true;

            }
        } 
    }
}